package com.game.springbootstart.service.impl;

import com.game.springbootstart.DTO.AdminDTO;
import com.game.springbootstart.constant.StatusConstant;
import com.game.springbootstart.entity.Admin;
import com.game.springbootstart.exception.AccountLockedException;
import com.game.springbootstart.exception.AccountNotFoundException;
import com.game.springbootstart.exception.PasswordErrorException;
import com.game.springbootstart.mapper.AdminMapper;
import com.game.springbootstart.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-09
 */
@Service
public class AdminServiceImpl extends ServiceImpl<com.game.springbootstart.mapper.AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin login(AdminDTO adminDTO) {
        String username = adminDTO.getUsername();
        String password = adminDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Admin admin = adminMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException("账号不存在");
        }

        //密码比对
        //对前端传过来的密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException("密码错误");
        }

        if (Objects.equals(admin.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException("账号被锁定");
        }

        //3、返回实体对象
        return admin;
    }

    @Override
    public Admin listByName(String name) {
        return adminMapper.listByName(name);
    }

    @Override
    public Admin getAdminByUsername(String currentUsername) {
        return adminMapper.getByUsername(currentUsername);
    }

    @Override
    public Admin listById(Long id) {
        return adminMapper.listById(id);
    }
}

